//
//  RW_PlayerView.m
//  SleepApp
//
//  Created by chuangqi on 2021/3/30.
//  Copyright © 2021 RiceWang. All rights reserved.
//

#import "RW_PlayerView.h"
#import "RW_PushPlayersTools.h"
#import "RW_AddSongToSingleView.h"
#import "RW_PlayerViewModel.h"

/** 默认播放器播放模式Key */
static NSString * DefaultRunloopTypeKey = @"DefaultRunloopTypeKey";


@interface RW_PlayerView (){
    //进度条拖动状态
    BOOL _isPhase;
    //当前播放列表音频模型
    NSArray<RW_SongModel *> *_audio_list_model;
    //当前显示的音频模型
    RW_SongModel *_now_show_model;
}
/** VM */
@property (nonatomic,strong) RW_PlayerViewModel *wlclass_view_model;
/** 进度条 */
@property (nonatomic,strong) UISlider *slider_view;
/** 下载进度条 */
@property (nonatomic,strong) UIProgressView *progress_view;
/** 上一首 */
@property (nonatomic,strong) UIButton *less_button;
/** 播放暂停 */
@property (nonatomic,strong) UIButton *play_stop_button;
/** 下一首 */
@property (nonatomic,strong) UIButton *next_button;
/** 循环方式 */
@property (nonatomic,strong) UIButton *runloop_type_button;
/** 收藏 */
@property (nonatomic,strong) UIButton *collection_button;
/** 歌曲背景板列表 */
@property (nonatomic,strong) WLCollectionView *wlclass_collection_view;
@end

@implementation RW_PlayerView
- (instancetype)init{
    self = [super init];
    if (self) {
        self.backgroundColor = UIColor.whiteColor;
        [self addSubview:self.wlclass_collection_view];
        [self addSubview:self.progress_view];
        [self addSubview:self.slider_view];
        [self addSubview:self.less_button];
        [self addSubview:self.play_stop_button];
        [self addSubview:self.next_button];
        [self addSubview:self.runloop_type_button];
        [self addSubview:self.collection_button];
        
        [self.progress_view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self.slider_view);
            make.bottom.mas_equalTo(self);
        }];
        [self.slider_view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.right.mas_equalTo(self);
            make.bottom.mas_equalTo(self).mas_offset(-100);
        }];
        [self.less_button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.play_stop_button.mas_bottom).mas_offset(20);
            make.left.mas_equalTo(self).mas_offset(50);
            make.size.mas_equalTo(CGSizeMake(50, 50));
        }];
        [self.play_stop_button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.mas_equalTo(self);
            make.centerY.mas_equalTo(self).mas_offset(-Main_Screen_Width/4);
            make.size.mas_equalTo(CGSizeMake(100, 100));
        }];
        [self.next_button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.mas_equalTo(self.play_stop_button.mas_bottom).mas_offset(20);
            make.right.mas_equalTo(self).mas_offset(-50);
            make.size.mas_equalTo(CGSizeMake(50, 50));
        }];
        [self.runloop_type_button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(self).mas_offset(- 10 - kBottomSafeHeight);
            make.left.mas_equalTo(self).mas_offset(10);
            make.size.mas_equalTo(CGSizeMake(50, 50));
        }];
        [self.collection_button mas_makeConstraints:^(MASConstraintMaker *make) {
            make.bottom.mas_equalTo(self).mas_offset(-10 - kBottomSafeHeight);
            make.right.mas_equalTo(self).mas_offset(-10);
            make.size.mas_equalTo(CGSizeMake(50, 50));
        }];
        [self.wlclass_collection_view mas_makeConstraints:^(MASConstraintMaker *make) {
            make.edges.insets(UIEdgeInsetsZero);
        }];
    }
    return self;
}
/** 数据绑定 初始化事件 */
-(void)setWlclass_players_model:(RW_Players *)wlclass_players_model{
    _wlclass_players_model = wlclass_players_model;
    /** 音频列表 */
    [RACObserve(_wlclass_players_model, songList) subscribeNext:^(NSArray<RW_SongModel *> *songList) {
        if (songList){
            [self initSongList:songList];
        }
    }];
    /** 当前播放的音频模型 只读 */
    [RACObserve(_wlclass_players_model, play_song) subscribeNext:^(RW_SongModel *play_song) {
        if (play_song){
            [self initNowPlaySongInfo:play_song];
        }
    }];
    /** 当前播放的音频总秒数 只读 */
    [RACObserve(_wlclass_players_model, play_all_second) subscribeNext:^(id play_all_second_t) {
        NSInteger play_all_second = [play_all_second_t integerValue];
        if (play_all_second){
            self.slider_view.maximumValue = play_all_second;
        }
    }];
    /** 当前播放状态 只读 */
    [RACObserve(_wlclass_players_model, play_status_type) subscribeNext:^(id play_status_type_t) {
        Player_Status_Type play_status_type = (Player_Status_Type)[play_status_type_t intValue];
        NSLog(@"当前状态：%lu",(unsigned long)play_status_type);
        [self changePlayStatus:play_status_type];
    }];
    /** 当前下载进度  play_status_type 为 Player_Status_Type_Download 才有效  只读 */
    [RACObserve(_wlclass_players_model, play_download_progress) subscribeNext:^(id play_download_progress_t) {
        float play_download_progress = [play_download_progress_t floatValue];
        if (play_download_progress){
            NSLog(@"下载进度：%f",play_download_progress);
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.progress_view setProgress:play_download_progress animated:true];
            });
        }
    }];
    /** 前播放循环模式 读写 */
    [RACObserve(_wlclass_players_model, play_runLoop_type) subscribeNext:^(id play_runLoop_type_t) {
        Player_RunLoop_Type play_runLoop_type = (Player_RunLoop_Type)[play_runLoop_type_t intValue];
        [self changeRunLoopType:play_runLoop_type];
    }];
    /** 当前播放的音频的秒数 修改当前播放的进度 读写 */
    [RACObserve(_wlclass_players_model, play_second) subscribeNext:^(id play_second_t) {
        NSInteger play_second = [play_second_t integerValue];
        if (play_second && !self->_isPhase){
            [self.slider_view setValue:play_second];
        }
    }];
    /** 当前播放的音频下标 修改当前播放的下标 读写  */
    [RACObserve(_wlclass_players_model, play_index) subscribeNext:^(id play_index_t) {
        NSInteger play_index = [play_index_t integerValue];
        [self changePlayIndex:play_index];
    }];
}


/*
 // MPMediaItemPropertyAlbumTitle           专辑标题
 // MPMediaItemPropertyAlbumTrackCount      声道个数
 // MPMediaItemPropertyAlbumTrackNumber     左右声道
 // MPMediaItemPropertyArtist               艺术家(歌曲作者)
 // MPMediaItemPropertyArtwork              锁屏界面的封面
 // MPMediaItemPropertyComposer
 // MPMediaItemPropertyDiscCount
 // MPMediaItemPropertyDiscNumber
 // MPMediaItemPropertyGenre
 // MPMediaItemPropertyPersistentID
 // MPMediaItemPropertyPlaybackDuration     播放时长
 // MPMediaItemPropertyTitle
 */
#pragma mark -- 主动操作事件
/** 修改播放进度 */
- (void)sliderValurChanged:(UISlider*)slider forEvent:(UIEvent*)event {
    UITouch *touchEvent = [[event allTouches] anyObject];
        switch (touchEvent.phase) {
            case UITouchPhaseBegan:
                _isPhase = YES;
//                NSLog(@"开始拖动");
                break;
//            case UITouchPhaseMoved:
//                NSLog(@"正在拖动");
//                break;
            case UITouchPhaseEnded:
                _isPhase = NO;
                [self.wlclass_players_model change_play_second:(int)slider.value];
//                NSLog(@"%f",slider.value);
//                NSLog(@"结束拖动");
                break;
            default:
                break;
        }
}
/** 上一首 */
-(void)lessClickButton:(UIButton *)sender{
    [self.wlclass_players_model lessPlayIndex];
}
/** 播放或者暂停 */
-(void)playClickButton:(UIButton *)sender{
    switch (self.wlclass_players_model.play_status_type) {
        case Player_Status_Type_Default://等待播放
        case Player_Status_Type_InitData://等待播放
        case Player_Status_Type_Stoping:{//暂停
            //点击开始播放的时候停止其他播放器的播放状态
            [RW_PushPlayersTools stopOtherPlay];
            //开始播放内容
            [self.wlclass_players_model beginPlay];
            //将单利播放器替换为当前的播放器
            if (![self.roowViewController isEqual:[RW_PlayerViewController sharedInstance]]){
                [RW_PlayerViewController realodPlayerViewController:self.roowViewController];
            }
        }
            break;
        case Player_Status_Type_Playing:{//正在播放
            //暂停播放
            [self.wlclass_players_model stopPlay];
        }
            break;
        case Player_Status_Type_Error:{//播放失败或者下载失败
            //开始播放
            [self.wlclass_players_model beginPlay];
        }
            break;
        case Player_Status_Type_Download://下载状态
        default:
            break;
    }
}
/** 下一首 */
-(void)nextClickButton:(UIButton *)sender{
    [self.wlclass_players_model nextPlayIndex];
}
/** 循环方式 */
-(void)runloopClickButton:(UIButton *)sender{
    Player_RunLoop_Type type = (Player_RunLoop_Type)[UserDefaults_wl integerForKey:DefaultRunloopTypeKey];
    switch (type) {
        case Player_RunLoop_Type_Default:{//默认播放模式 列表循环
            [UserDefaults_wl setInteger:Player_RunLoop_Type_Circulation forKey:DefaultRunloopTypeKey];
        }
            break;
        case Player_RunLoop_Type_Circulation:{//单曲循环
            [UserDefaults_wl setInteger:Player_RunLoop_Type_Random forKey:DefaultRunloopTypeKey];
        }
            break;
        case Player_RunLoop_Type_Random:{//随机播放
            [UserDefaults_wl setInteger:Player_RunLoop_Type_Default forKey:DefaultRunloopTypeKey];
        }
            break;
        default:
            break;
    }
    [UserDefaults_wl synchronize];
    [self.wlclass_players_model change_runLoop_type:(Player_RunLoop_Type)[UserDefaults_wl integerForKey:DefaultRunloopTypeKey]];
    [self changeRunLoopType:(Player_RunLoop_Type)[UserDefaults_wl integerForKey:DefaultRunloopTypeKey]];
}
/** 添加到歌单 */
-(void)collectionClickButton:(UIButton *)sender{
    RW_AddSongToSingleView.init_wl()
    .maskAlpha_wl(.5f)
    .rootViewController_wl([self viewController_wl])
    .addData_wl(_now_show_model)
    .closeBlock_wl(^(id data){
        NSLog(@"关闭:%@",data);
    })
    .show_wl();
}


#pragma mark -- 被动数据修改导致的显示内容变更事件
/** 初始化音频列表 */
-(void)initSongList:(NSArray<RW_SongModel *> *)songList{
    _audio_list_model = songList;
    if (!songList){  return; }
    if (!songList.count){ return; }
    self.next_button.hidden = (songList.count <= 1);
    self.less_button.hidden = (songList.count <= 1);
    self.runloop_type_button.hidden = (songList.count <= 1);
    [self.wlclass_view_model getView:songList success:^(NSArray<WLBaseCollectionViewLayerSection *> * _Nonnull response) {
        [self.wlclass_collection_view setAllSection:response];
    }];
}
/** 初始化当前播放音频 */
-(void)initNowPlaySongInfo:(RW_SongModel *)song{
    _now_show_model = song;
}
/** 修改播放文本图标状态 */
-(void)changePlayStatus:(Player_Status_Type)type{
    switch (type) {
        case Player_Status_Type_InitData://数据初始化完成
        case Player_Status_Type_Default:{//等待播放
            [self.play_stop_button setImage:[UIImage svgName:@"player_play_icon"] forState:UIControlStateNormal];
            [self.slider_view setValue:0];
        }
            break;
        case Player_Status_Type_Stoping:{//暂停
            [self.play_stop_button setImage:[UIImage svgName:@"player_play_icon"] forState:UIControlStateNormal];
        }
            break;
        case Player_Status_Type_Playing:{//正在播放
            [self.play_stop_button setImage:[UIImage svgName:@"player_stop_icon"] forState:UIControlStateNormal];
            [self.progress_view setProgress:1 animated:true];
        }
            break;
        case Player_Status_Type_Download:{//下载状态
            [self.play_stop_button setImage:[UIImage svgName:@"player_download_icon"] forState:UIControlStateNormal];
            [self.progress_view setProgress:0 animated:false];
        }
            break;
        case Player_Status_Type_Error:{//播放失败或者下载失败
            [self.play_stop_button setImage:[UIImage svgName:@"player_reload_download_icon.svg"] forState:UIControlStateNormal];
            [self.progress_view setProgress:0 animated:true];
        }
            break;
        default:
            [self.play_stop_button setTitle:@"奇怪的状态" forState:UIControlStateNormal];
            break;
    }
    self.progress_view.hidden = (self.progress_view.progress >= 1);
}
/** 修改循环模式的显示内容 */
-(void)changeRunLoopType:(Player_RunLoop_Type)type{
    switch (type) {
        case Player_RunLoop_Type_Default:{//默认播放模式 列表循环
            [self.runloop_type_button setImage:[UIImage svgName:@"player_list_icon"] forState:UIControlStateNormal];
        }
            break;
        case Player_RunLoop_Type_Circulation:{//单曲循环
            [self.runloop_type_button setImage:[UIImage svgName:@"player_circulation_icon"] forState:UIControlStateNormal];
        }
            break;
        case Player_RunLoop_Type_Random:{//随机播放
            [self.runloop_type_button setImage:[UIImage svgName:@"player_random_icon"] forState:UIControlStateNormal];
        }
            break;
        default:
            [self.runloop_type_button setTitle:@"奇怪的状态" forState:UIControlStateNormal];
            break;
    }
}
/** 切换指定的播放音频 */
-(void)changePlayIndex:(NSInteger)play_index{
    NSLog(@"当前播放下表：%ld",play_index);
    [self.wlclass_collection_view scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:play_index inSection:0] atScrollPosition:UICollectionViewScrollPositionNone animated:YES];
}


#pragma mark -- 懒加载
-(UISlider *)slider_view{
    if (!_slider_view){
        _slider_view = [[UISlider alloc]init];
        _slider_view.backgroundColor = UIColor.randomColor;
        [_slider_view addTarget:self action:@selector(sliderValurChanged:forEvent:) forControlEvents:UIControlEventValueChanged];
        _slider_view.hidden = YES;
    }
    return _slider_view;
}
-(UIProgressView *)progress_view{
    if (!_progress_view){
        _progress_view = [[UIProgressView alloc]init];
        // 设置走过的进度条的颜色
        _progress_view.progressTintColor = HexColor(@"5564BE");
        // 设置未走的进度条的颜色
        _progress_view.trackTintColor = [UIColor clearColor];
    }
    return _progress_view;
}
-(UIButton *)less_button{
    if (!_less_button){
        _less_button = [[UIButton alloc]init];
        [_less_button setImage:[UIImage svgName:@"player_less_icon"] forState:UIControlStateNormal];
        [_less_button addTarget:self action:@selector(lessClickButton:) forControlEvents:UIControlEventTouchUpInside];
        _less_button.hidden = true;
    }
    return _less_button;
}
-(UIButton *)play_stop_button{
    if (!_play_stop_button){
        _play_stop_button = [[UIButton alloc]init];
        [_play_stop_button addTarget:self action:@selector(playClickButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _play_stop_button;
}
-(UIButton *)next_button{
    if (!_next_button){
        _next_button = [[UIButton alloc]init];
        [_next_button setImage:[UIImage svgName:@"player_next_icon"] forState:UIControlStateNormal];
        [_next_button addTarget:self action:@selector(nextClickButton:) forControlEvents:UIControlEventTouchUpInside];
        _next_button.hidden = true;

    }
    return _next_button;
}
-(UIButton *)runloop_type_button{
    if (!_runloop_type_button){
        _runloop_type_button = [[UIButton alloc]init];
        [_runloop_type_button addTarget:self action:@selector(runloopClickButton:) forControlEvents:UIControlEventTouchUpInside];
        _runloop_type_button.hidden = true;

        Player_RunLoop_Type type = (Player_RunLoop_Type)[UserDefaults_wl integerForKey:DefaultRunloopTypeKey];
        [self changeRunLoopType:type];
    }
    return _runloop_type_button;
}
-(UIButton *)collection_button{
    if (!_collection_button){
        _collection_button = [[UIButton alloc]init];
        [_collection_button setImage:[UIImage svgName:@"player_collection_icon"] forState:UIControlStateNormal];
        [_collection_button addTarget:self action:@selector(collectionClickButton:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _collection_button;
}
-(WLCollectionView *)wlclass_collection_view{
    if (!_wlclass_collection_view){
        _wlclass_collection_view = [WLCollectionView initWithHorizontalDelegate:self];
        _wlclass_collection_view.userInteractionEnabled = NO;
//        _wlclass_collection_view.alpha = .7f;
    }
    return _wlclass_collection_view;
}
-(RW_PlayerViewModel *)wlclass_view_model{
    if (!_wlclass_view_model){
        _wlclass_view_model = [[RW_PlayerViewModel alloc]init];
    }
    return _wlclass_view_model;
}

#pragma mark -- 释放当前播放器属性
-(void)releaseVM{
    [_wlclass_players_model releaseVM];
    _wlclass_players_model = nil;
    [self.subviews enumerateObjectsUsingBlock:^(__kindof UIView * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
        obj = nil;
    }];
}
@end
